// Copyright (c) 2010 Manuel Peinado Gallego <manuel.peinado@gmail.com>
// Distributed under the MIT license

#include "stdafx.h"
#include "WorldBuilder.h"
#include "GeometryNode.h"
#include "Sphere.h"
#include "AABB.h"
#include "Material.h"
#include "View3d.h"
#include "MaterialManager.h"
#include "GeometryFactory.h"
#include "TextureTransform.h"
#include "ShaderProgram.h"


GeometryNode::GeometryNode()
{
}

GeometryNode::~GeometryNode()
{
}

//  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  

ref<Geometry> GeometryNode::getGeometry() const 
{ 
    return m_geo; 
}

void GeometryNode::setGeometry(ref<Geometry> geo) 
{ 
    m_geo = geo; 
    notifyPropertyChange(NodeEvent::NodeGeometry);
}

//  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  

void GeometryNode::draw(View3d* view) const 
{
    if(m_geo == NULL)
    {
        return;
    }
    
    if(view->isDrawingInPickMode())
    {
        PickColor c = getPickColor();
        c.setInRenderContext();
    }

    m_geo->draw(view);
}

//  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  

AABB GeometryNode::getAabbLocalImpl() const
{
    ASSERT(m_geo);
    return m_geo->getAABB();
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Serialization

void GeometryNode::read(std::wistream& is)
{
    /*
    TransformNode::read(is);
    
    // We store the material name because id will change when 
    // the program is re-run
    
    // TODO find a more elegant way to access the material manager from here
    NodeManager& nodeMngr = *getNodeManager();
    MaterialManager& matMngr = nodeMngr.getWorld()->getMaterialManager();
    
    std::wstring matName;
    is >> matName >> m_wireframe;

    Material* mat = matMngr.getMaterialByName(matName);
    ASSERT(mat != NULL);
    
    ASSERT("include back material!" == 0);
    m_frontMaterialId = mat->getId();

    m_geo = GeometryFactory::read(is);
    */
}

void GeometryNode::write(std::wostream& os) const
{
    /*
    TransformNode::write(os);
    
    // We store the material name because id will change when 
    // the program is re-run
    
    // TODO find a more elegant way to access the material manager from here
    NodeManager* nodeMngr = getNodeManager();
    MaterialManager& matMngr = nodeMngr->getWorld()->getMaterialManager();
    
    Material* mat = matMngr.getMaterialById(m_frontMaterialId);
    ASSERT("include back material!" == 0);
    ASSERT(mat != NULL);

    os << mat->getName() << "\n" << m_wireframe << "\n";
    GeometryFactory::write(os, *m_geo);
    */
}

